/* t_json.cpp : test dgnsc json
 * Copyright (C) 2011 drangon <drangon.zhou@gmail.com>
 * 2011-09
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dgnsc/json.h>

#include "gtest.h"

#include <stdio.h>
// #include <assert.h>
#include <string.h>

static const char s_j1[] = "[ null, true, false, \r\n"
	" /* common-1 */\r\n"
	" // common-2 \r\n"
	"  256\t,\t\r\n"
	"-345.2e+67, \"aa\\\"bb\", [], [null],\r\n"
	"{ \"aa\" : null, \"bb\": \"str\", \"cc\" : [null,true] } \r\n"
	" ] \t  ";

TEST( json, json )
{
	int used_len;
	dgn_json_t jv = dgn_json_init_parse( s_j1, &used_len );
	printf( "jv %p, used_len %d, remain [%s]\n", jv, used_len, s_j1 + used_len );
	EXPECT_TRUE( jv != NULL );

	enum dgn_json_type_e type = dgn_json_get_type(jv);
	int num = dgn_json_get_array_num( jv );
	int vi = dgn_json_get_int( dgn_json_get_array( jv, 3 ) );
	double vd = dgn_json_get_double( dgn_json_get_array( jv, 3 ) );
	const char * str = dgn_json_get_string( dgn_json_get_array( jv, 5 ) );
	printf( "type %d, num %d, int %d, double %f, str [%s]\n", (int)type, num, vi, vd, str );

	dgn_json_t sub = dgn_json_get_array( jv, 0 );
	dgn_json_set_type( sub, DGN_JSON_ARRAY );

	sub = dgn_json_get_array( jv, 1 );
	dgn_json_set_string( sub, "set true", -1 );

	sub = dgn_json_init_dup( dgn_json_get_array( jv, 2 ) );
	dgn_json_t ret_sub = NULL;
	// sub will must not belong to other, and will release by jv
	// but ret_sub no longer belong to jv, must free by outside
	dgn_json_set_array_ex( jv, 4, sub, &ret_sub );
	dgn_json_fini( ret_sub );

	dgn_str_t buf = dgn_str_init( 20 );
	dgn_json_output( jv, buf );
	printf( "output : <%s>\n", dgn_str_c( buf ) );
	dgn_str_fini( buf );
	dgn_json_fini( jv ), jv = NULL;
}

